<script setup lang="ts">
import RoomStatus from './components/RoomStatus.vue'
import RoomAction from './components/RoomAction.vue'
import RoomMessage from './components/RoomMessage.vue'
import io from 'socket.io-client'
import type { Socket } from 'socket.io-client'
import { baseURL } from '@/utils/request'
import { useUserStore } from '@/stores'
import { useRoute } from 'vue-router'
import { onUnmounted, onMounted, ref, nextTick } from 'vue'
import type { Message, TimeMessages } from '@/types/room.d'
import { MsgType, OrderType } from '@/enums'
import { getConsultOrderDetail } from '@/services/consult'
import type { ConsultOrderItem, Image } from '@/types/consult'
import dayjs from 'dayjs'
import { showToast } from 'vant'
import { provide } from 'vue'
// 测试socket.io
// 参数1：不传默认是当前服务域名，开发中传入服务器地址
// 参数2：配置参数，根据需要再来介绍
// const socket = io('地址')

// 确定建立连接是否成功
// socket.on('connect', () => {
// 连接成功
// })

// 如何发消息  sendMsg 事件名是跟后端约定好的
// socket.emit('sendMsg', '我是个消息')
// socket.emit('sendMsg1', '我是个消息')
// socket.emit('sendMsg2', { a: 1, b: 2 })

// 接受消息
// socket.on('receiveMsg', (e) => {
// e就是服务端触发 receiveMsg 发过来的数据
// })
// 离开组件时需要断开连接
// socket.close()

// 1. 初始化socket
// 2. 检测连接是否成功  对失败或者断开连接进行监听
// 3. 组件销毁前必须断开连接
const store = useUserStore()
const route = useRoute()
let socket: Socket

const list = ref<Message[]>([])
const time = ref(dayjs().format('YYYY-MM-DD HH:mm:ss'))
const initFlag = ref(true)
onMounted(() => {
  socket = io(baseURL, {
    auth: {
      token: `Bearer ${store.user?.token}`
    },
    query: {
      orderId: route.query.orderId
    }
  })
  socket.on('connect', () => {
    // 建立连接成功
    console.log('建立连接成功')
    list.value = []
  })
  socket.on('error', (err) => {
    // 监听错误
    console.log(err)
  })

  socket.on('disconnect', () => {
    // 监听断开连接
    console.log('已经断开连接了')
  })

  // 聊天记录
  socket.on('chatMsgList', ({ data }: { data: TimeMessages[] }) => {
    console.log(data)
    // 默认返回数据没有时间这一条 所以我们自己拼一下
    const arr: Message[] = []
    data.forEach((item, i) => {
      if (i === 0) time.value = item.createTime
      arr.push({
        msgType: MsgType.Notify,
        msg: {
          content: item.createTime
        },
        createTime: item.createTime,
        id: item.createTime
      })
      arr.push(...item.items)
    })
    list.value.unshift(...arr)
    // 下拉加载
    loading.value = false
    if (!data.length) {
      return showToast('没有聊天记录了')
    }
    nextTick(() => {
      if (initFlag.value) {
        socket.emit('updateMsgStatus', arr[arr.length - 1].id)
        window.scrollTo(0, document.body.scrollHeight)
        initFlag.value = false
      }
    })
  })

  // 问诊室状态变化监听
  socket.on('statusChange', () => loadConsult())

  // 接受聊天消息
  socket.on('receiveChatMsg', async (e) => {
    console.log(e)
    socket.emit('updateMsgStatus', e.id)
    list.value.push(e)
    await nextTick()
    window.scrollTo(0, document.body.scrollHeight)
  })
})

// 获取订单数据
const consult = ref<ConsultOrderItem>()
const loadConsult = async () => {
  const res = await getConsultOrderDetail(route.query.orderId as string)
  consult.value = res.data
}

onMounted(() => {
  loadConsult()
})
// 当组件销毁时必须断开连接
onUnmounted(() => {
  socket.close()
})

// 发送文字消息
const onSendText = (text: string) => {
  console.log(text)
  // socket.emit  客户端发送给服务端
  socket.emit('sendChatMsg', {
    from: store.user?.id,
    to: consult.value?.docInfo?.id,
    // 注意key值是msgType  不是MsgType
    msgType: MsgType.MsgText,
    msg: {
      content: text
    }
  })
}
// 发送图片消息
const onSendImage = (image: Image) => {
  socket.emit('sendChatMsg', {
    from: store.user?.id,
    to: consult.value?.docInfo?.id,
    // 注意key值是msgType  不是MsgType
    msgType: MsgType.MsgImage,
    msg: {
      picture: image
    }
  })
}

// 下拉刷新
const loading = ref(false)
const onRefresh = () => {
  console.log(111)
  socket.emit('getChatMsgList', 20, time.value, route.query.orderId)
}

// 给后代组件提供数据
provide('consult', consult)
const completeEva = (score: number) => {
  const item = list.value.find((item) => item.msgType === MsgType.CardEvaForm)
  if (item) {
    item.msg.evaluateDoc = { score }
    item.msgType = MsgType.CardEva
  }
}
provide('completeEva', completeEva)
</script>

<template>
  <div class="room-page">
    <cp-nav-bar title="问诊室" />
    <room-status
      :status="consult?.status as OrderType"
      :countdown="consult?.countdown as number"
    ></room-status>
    <van-pull-refresh v-model="loading" @refresh="onRefresh">
      <room-message :list="list" />
    </van-pull-refresh>

    <room-action
      :disabled="consult?.status !== OrderType.ConsultChat"
      @send-text="onSendText"
      @send-image="onSendImage"
    ></room-action>
  </div>
</template>

<style lang="scss" scoped>
.room-page {
  padding-top: 90px;
  padding-bottom: 60px;
  min-height: 100vh;
  box-sizing: border-box;
  background-color: var(--cp-bg);
  .van-pull-refresh {
    width: 100%;
    min-height: calc(100vh - 150px);
  }
}
</style>
